﻿using Apps.BLL.HC;
using Apps.BLL.HuaChan;
using Apps.Common;
using Apps.Locale;
using Apps.Models;
using Apps.Models.HuaChan;
using Apps.Web.Core;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Wantn.FIS.Enum;

namespace Apps.Web.Areas.HuaChan.Controllers
{
    public class HuaChanDataController : BaseController
    {
        HC_EXTEND_FIELD_BLL bll = new HC_EXTEND_FIELD_BLL();
        HC_ITEM_EXTEND_REL_BLL relBll = new HC_ITEM_EXTEND_REL_BLL();
        HC_ITEMS_BLL itemsBll = new HC_ITEMS_BLL();
        HC_FORM_BLL formBll = new HC_FORM_BLL();
        readonly HC_FORM_REFERENCE_VALUE_BLL fvBll = new HC_FORM_REFERENCE_VALUE_BLL();
        readonly HC_EXAMINE_BLL examineBll = new HC_EXAMINE_BLL();

        HUACHAN_BLL huachanBll = new HUACHAN_BLL();

        ValidationErrors errors = new ValidationErrors();
        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [SupportFilter(ActionName = "Index")]
        [HttpPost]
        public string GetItemList()
        {
            string queryStr = Utils.ObjectToStr(Request["queryStr"]);
            //List<HC_ITEMS> itemList = itemsBll.GetList(queryStr);
            List<HUACHAN_PROJECT> itemList = huachanBll.GetNopageList(queryStr);
            return JsonConvert.SerializeObject(itemList);
        }

        //--------------------------------------------

        [SupportFilter(ActionName = "Index")]
        public string GetList()
        {
            string beginTime = Utils.ObjectToStr(Request["beginTime"]);
            string endTime = Utils.ObjectToStr(Request["endTime"]);
            int formState = Utils.ObjToInt(Request["formState"], -2);
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            int pageSize = Utils.ObjToInt(Request["rows"], 15);
            int pageIndex = Utils.ObjToInt(Request["page"], 1);
            string sort = Utils.ObjectToStr(Request["sort"]);
            string order = Utils.ObjectToStr(Request["order"]);
            System.Data.DataTable list = formBll.GetList(itemId, beginTime, endTime, formState, pageIndex, pageSize, sort, order);
            int totalCount = formBll.GetCount(itemId, beginTime, endTime, formState);
            var JsonString = new StringBuilder();

            if (list.Rows.Count > 0)
            {
                JsonString.Append("[");
                for (int i = 0; i < list.Rows.Count; i++)
                {
                    JsonString.Append("{");
                    for (int j = 0; j < list.Columns.Count; j++)
                    {
                        if (j < list.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + list.Columns[j].ColumnName.ToString() + "\":" + "\"" + list.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == list.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + list.Columns[j].ColumnName.ToString() + "\":" + "\"" + list.Rows[i][j].ToString() + "\"");
                        }
                    }

                    if (i == list.Rows.Count - 1)
                    {
                        JsonString.Append(",\"fieldList\":" + JsonConvert.SerializeObject(fvBll.Get_FORM_REFERENCE_VALUE_List(list.Rows[i]["ID"].ToString())) + "");
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append(",\"fieldList\":" + JsonConvert.SerializeObject(fvBll.Get_FORM_REFERENCE_VALUE_List(list.Rows[i]["ID"].ToString())) + "");
                        JsonString.Append("},");
                    }
                }
                JsonString.Append("]");
            }
            //string SS=JsonString.ToString();
            //return JsonString.ToString();

            StringBuilder jsonSb = new StringBuilder();
            jsonSb.Append("{");
            if (list != null && list.Rows.Count > 0)
            {
                jsonSb.Append(string.Format("\"total\":{0},\"rows\":{1}", totalCount, JsonString.ToString()));
            }
            else
            {
                jsonSb.Append("\"total\":0,\"rows\":[]");
            }
            //jsonSb.Append(string.Format("\"total\":{0},\"rows\":{1}", totalCount, JsonHandler.DataTableToJson(list)));
            jsonSb.Append("}");
            string json = jsonSb.ToString().Replace("\\", "").Replace("\"[", "").Replace("]\"", "");
            return json;
        }

        [SupportFilter(ActionName = "Index")]
        public string GetFiledList()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            return JsonConvert.SerializeObject(fieldList);
        }
        [SupportFilter(ActionName = "Index")]
        public string GetFormFiledValue()
        {
            string formId = Utils.ObjectToStr(Request["formId"]);
            string field = Utils.ObjectToStr(Request["field"]);
            FORM_REFERENCE_VALUE formValue = fvBll.Get_FORM_REFERENCE_VALUE(formId, field);
            return JsonConvert.SerializeObject(formValue);
        }

        [SupportFilter(ActionName = "Index")]
        public string GetExamineReason()
        {
            string formId = Utils.ObjectToStr(Request["formId"]);
            return examineBll.GetExamineReason(formId);
        }

        #region 创建
        [SupportFilter]
        public ActionResult Create(string projectId)
        {
            List<HUACHAN_PROJECT_FIELDS> fileds = huachanBll.GetListDetail(projectId);
            ViewBag.projectId = projectId;
            return View(fileds);
        }

        [HttpPost]
        [SupportFilter(ActionName = "Create")]
        public JsonResult Create(HUACHAN_PROJECT_DATA model)
        {
            model.ADDTIME = DateTime.Now;
            model.ID = ResultHelper.NewId;
            model.EXAMINE = "未审核";
            if (string.IsNullOrEmpty(model.PROJECTID))
            {
                return Json(JsonHandler.CreateMessage(0, "未指定表单主编号!"));
            }
            model.EXMINETIME = ""; 
            if (huachanBll.AddProjectData(model))
            {
                return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
            }
            else
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
            }
        }
        #endregion

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string projectId, string dataId)
        {
            List<HUACHAN_PROJECT_FIELDS> fileds = huachanBll.GetListDetail(projectId);
            DataTable data = huachanBll.GetProjectDataTable(dataId);
            for (int i = 0; i < fileds.Count; i++)
            {
                fileds[i].vaule = data.Rows[0][$"DATA{fileds[i].COLUMNIDX}"].ToString();
            }
            ViewBag.projectId = projectId;
            ViewBag.dataId = dataId;
            return View(fileds);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(HUACHAN_PROJECT_DATA model)
        {
            if (string.IsNullOrEmpty(model.PROJECTID))
            {
                return Json(JsonHandler.CreateMessage(0, "未指定表单主编号!"));
            }

            var info = huachanBll.GetProjectData(model.ID);
            if (info.EXAMINE == "审核通过")
            {
                return Json(JsonHandler.CreateMessage(0, "审核通过的数据不允许修改"));
            }

            if (huachanBll.UpdateProjectData(model))
            {
                return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
            }
            else
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
            }
        }
        #endregion

        #region 审核
        [SupportFilter]
        public ActionResult Examine(string projectId, string dataIds)
        {
            ViewBag.projectId = projectId;
            ViewBag.dataIds = dataIds;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Examine(string projectId, string dataIds, string examine)
        {
            try
            {
                List<string> ids = dataIds.Split(',').ToList();
                if (ids.Count <= 0)
                {
                    return Json(JsonHandler.CreateMessage(0, "请至少选择一项"));
                }
                if (huachanBll.ExamineProjectData(ids, examine))
                {
                    return Json(JsonHandler.CreateMessage(1, "报单审核成功"));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    return Json(JsonHandler.CreateMessage(0, "报单审核失败" + ErrorCol));
                }
            }
            catch
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, "报单审核失败" + ErrorCol));
            }
        }
        #endregion

        #region 导出
        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData(EasyUIDataGridPostModel model)
        {
            var data = huachanBll.GetProjectData( "ADDTIME", "DESC", model.examine, model.projectId, model.beginTime, model.endTime);

            if (data != null && data.Count > 0)
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
        }

        /// <summary>
        /// 将list转换成DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="varlist"></param>
        /// <returns></returns>
        public DataTable ListToDataTable<T>(List<T> varlist)
        {
            DataTable dtReturn = new DataTable();
            // column names
            PropertyInfo[] oProps = null;
            // Could add a check to verify that there is an element 0
            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others will follow
                if (oProps == null)
                {
                    oProps = rec.GetType().GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;
                        if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }
                DataRow dr = dtReturn.NewRow();
                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
                }
                dtReturn.Rows.Add(dr);
            }
            return dtReturn;

            }

            [SupportFilter]
        public ActionResult Export(string examine, string projectId, string beginTime, string endTime)
        {

            var data = huachanBll.GetProjectData("ADDTIME", "DESC", examine, projectId, beginTime, endTime);
            var tabData = ListToDataTable(data);
            List<HUACHAN_PROJECT_FIELDS> fileds = huachanBll.GetListDetail(projectId);
            List<EasyUiDataGridColumnModel> colunms = new List<EasyUiDataGridColumnModel>();
           
 
            DataTable dataTable = new DataTable("tb");

            dataTable.Columns.Add(new DataColumn {  Caption= "编号", ColumnName= "编号" });
            dataTable.Columns.Add(new DataColumn { Caption = "审核状态", ColumnName = "审核状态" });
            dataTable.Columns.Add(new DataColumn { Caption = "审核时间", ColumnName = "审核时间" });
            dataTable.Columns.Add(new DataColumn { Caption = "添加时间", ColumnName = "添加时间" });
            fileds.ForEach(res =>
            {
                dataTable.Columns.Add(new DataColumn { Caption = res.FIELDNAME, ColumnName = res.FIELDNAME });
            });

            for (int i = 0; i < tabData.Rows.Count; i++)
            {
                var res = tabData.Rows[i];
                var row = dataTable.NewRow();
                row["编号"] = res["ID"];
                row["审核状态"] = res["EXAMINE"];  
                row["审核时间"] = res["EXMINETIME"];   
                row["添加时间"] = res["ADDTIME"];  
                fileds.ForEach(item =>
                {
                    row[item.FIELDNAME] = res[$"DATA{item.COLUMNIDX}"];
                });
                dataTable.Rows.Add(row);
            }
            var exportFileName = string.Concat(
                "化产数据导出",
                DateTime.Now.ToString("yyyyMMdd"),
                ".xlsx");
            return new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dataTable
            };
        }
        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string dataId)
        {
            if (!string.IsNullOrWhiteSpace(dataId))
            {
                var info = huachanBll.GetProjectData(dataId);
                if (info.EXAMINE == "审核通过")
                {
                    return Json(JsonHandler.CreateMessage(0, "审核通过的数据不允许删除"));
                }
                if (huachanBll.DelProjectData(dataId))
                {
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = "【删除失败】";
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
    }
}